<template>
	<div class="createWare w944">
		<alert ref="alert"></alert>
		<labelAll ref="labelAll" :LabelsIds="LabelsIds" :LabelsNames="LabelsNames" v-on:labelNamesChanges="reveiceChange($event)"></labelAll>
		<div class="label_top">
			<button @click="cancel"><i><&nbsp;</i>返回</button>
			<p>{{updateTitle}}</p>
		</div>
		<div class="coursewareContent">
			<div class="createWare_line">
				<span class="tit">课件名称：</span>
				<input placeholder="请输入课件名称" v-model="courseName"/>
			</div>
			<div class="createWare_line">
				<span class="tit">课件分类：</span>
				<el-select v-model="knowledgeMapTypeId" placeholder="请选择知识体系分类">
					<el-option v-for="item in knowledgeMapTypeIdArr" :key="item.id" :label="item.name" :value="item.id"></el-option>
				</el-select>
			</div>
			<div class="createWare_line">
				<span class="tit">章节学分：</span>
				<el-input placeholder="0-5分" v-model="courseUpgradeScore" style="ime-mode:disabled" onKeyUp="this.value=this.value.replace(/[^\.\d]/g,'');this.value=this.value.replace('.','');" @blur="getScore" id="score"></el-input> 
				<em>每个章节完成后学员获得的学分奖励</em>
			</div>
			<div class="createWare_line">
				<div style="overflow: hidden;">
					<span class="tit" style="float: left;">课程标签：</span>
					<div class="labelFour"><span v-for="item in this.LabelsNames">{{item}}</span></div>
					<a @click="openLabel" class="openLabel">选择标签</a>
				</div>
				<p class="labelWarn">最多可选四个标签</p>
			</div>
			<div class="createWare_line" v-if="isopen==1">
				<span class="tit">观看权限：</span>
				<el-checkbox-group v-model="checkedCities" style="display: inline-block;" @change="selectOptionLevel">
    				<el-checkbox v-for="item in optionLevel" :key="item.id" :label="item.id">{{item.name}}</el-checkbox>
 				</el-checkbox-group>
			</div>
			<div class="createWare_line platformLogo">
				<span class="tit">配图：</span>
				<div class="platformImg">
					<el-upload class="avatar-uploader" refs="uploadxls" action="http://www.h3clearning.com/huathree-back/uploadFile" :headers="myHeaders" :show-file-list="false" :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess">
						<img v-if="courseImg" :src="courseImg" class="avatar">
						<i v-else class="el-icon-plus avatar-uploader-icon"><b style="display:block;font-weight:normal"><em>上传图片</em></b></i>
					</el-upload>
					<em>建议尺寸为320*180像素，大小小于1M</em>
				</div>
			</div>
			<div class="createWare_line">
				<span style="margin-bottom: 25px;display: block;" class="tit">课件介绍：</span>
				<vue-ueditor-wrap v-model="courseDesc" :config="myConfig" style="margin-left: 74px;"></vue-ueditor-wrap>
			</div>
			<div class="footerButton">
				<a @click="checkSave" v-bind:style="{background: clickLock==true ? '#44CEF6' : '#3a8ee6'}">保存</a>
				<a @click="cancel" class="cancel">取消</a>
			</div>
		</div>
	</div>
</template>

<script>
	import alert from '../../components/Alert.vue';
	import labelAll from '../../components/label.vue';
	export default{
		data(){
			return{
				LabelsIds:[],
				LabelsNames:[],
				labelType:'createWare',
				isopen:0,
				clickLock:true,
				nowType: 'add',
				speakerId: '',
				updateTitle:'创建课件',
				id:'',
				courseName:'',
				permission:'',
				permissionArr:[],
				knowledgeMapTypeId:'',
				knowledgeMapTypeIdArr:[],
				lecture:'',
				lectureoption: [],
				lectureoptionCopy: [],
				courseUpgradeScore: '',
				checkedCities:[],
				optionLevel:[],
				checkedSelectionIds:[],
				skills: '',
				selectedItem: [],
				selectedId: [],
				subjects: [],
				courseImg: '',
				courseDesc: '',
				nickname: '',
				learnPoint: '',
				myHeaders:{Authorization:this.$root.userInfoMsg.sessionId},
				myConfig: {
					autoHeightEnabled: false,
					initialFrameHeight: 320,
					initialFrameWidth: '840'
				}
			}
		},
		methods:{
			getParams() {
				var routerParams = this.$route.params.type;
				this.speakerId = this.$route.params.speakerId;
				if(routerParams == 'edit') {
					this.nowType = 'edit';
					this.updateTitle = "编辑课件";
				} else {
					this.nowType = 'add';
				}
				console.log('createTeacherWare:',this.$route.params);
			},
			getScore(){
				if(this.courseUpgradeScore>5){
					this.$refs.alert.show({
						alertText: '学分最大值为5！',
						alertSubmit: function() {
							alertStatus: 0
						}
					});
					$('#score').focus();
				}
			},
			openLabel(){
				this.$refs.labelAll.labelTable=true;
			},
			reveiceChange(event){
				this.LabelsIds = event.arg1;
	        	this.LabelsNames = event.arg2;
	     	},
			add_type(){
				let that = this;
				var arr = this.LabelsIds.concat(this.checkedSelectionIds);
				let s= {
					rootcompanyid:1,
					courseName:that.courseName,
					knowledgeMapTypeId:that.knowledgeMapTypeId,
					speakerId:that.speakerId,
					courseUpgradeScore:that.courseUpgradeScore,
					courseImg:that.courseImg,
					courseLabels:arr.join(','),
					courseDesc:that.courseDesc
				};
				if(this.clickLock==true){
					this.clickLock=false;
					this.$ajax({
						url: this.$root.jifuUrl + '/mns/quanzi/addQuanziCourse',
						headers:{'ContentType': 'application/json; charset=utf-8'},
						data: s,					
						method: 'POST',
						success: res => {
							if(res.data.code == 200) {
								this.$refs.alert.show({alertText: '保存成功'});
								setTimeout(() =>{
									this.$router.push({
										name:'teacherMap'
									});
								},2000)
							}else{
								this.failText = res.data.message;
								this.$rootFunction().deleteResFail();
							}
						}
					});
				}
			},
			edit_type(){
				let that = this;
				var arr = this.LabelsIds.concat(this.checkedSelectionIds);
				let s= {
					id:that.id,
					rootcompanyid:1,
					courseName:that.courseName,
					knowledgeMapTypeId:that.knowledgeMapTypeId,
					speakerId:that.speakerId,
					courseUpgradeScore:that.courseUpgradeScore,
					courseImg:that.courseImg,
					courseLabels:arr.join(','),
					courseDesc:that.courseDesc
				};
				this.$ajax({
					url: this.$root.jifuUrl + '/mns/quanzi/updateQuanziCourse',
					headers:{'ContentType': 'application/json; charset=utf-8'},
					data: s,					
					method: 'POST',
					success: res => {
						if(res.data.code == 200) {
							this.$refs.alert.show({alertText: '保存成功'});
							setTimeout(() =>{
								this.$router.push({
									name:'teacherMap'
								});
							},2000)
						}else{
							this.failText = res.data.message;
							this.$rootFunction().deleteResFail();
						}
					}
				});
			},
			checkSave(){
				let that = this;
				if (that.nowType == 'add') {
					that.add_type();
				} else if (that.nowType == 'edit') {
					this.edit_type();
				}
			},
			cancel() {
				this.$router.go(-1);
			},
			//获取属性的id
			selectOptionLevel(){
				this.checkedSelectionIds = [];//复选框选中id
				for(var i = 0;i<this.checkedCities.length;i++){
					this.optionLevel.forEach(element => {
						if(element.id==this.checkedCities[i]){
							this.checkedSelectionIds.push(element.id);
						}
					});
				}
			},
			selectSearch(val){
				this.value = val;
		        if (val) { 
		            this.lectureoption = this.lectureoptionCopy.filter((item) => {
		                if (!!~item.nickname.indexOf(val) || !!~item.nickname.toUpperCase().indexOf(val.toUpperCase())) {
		                	return true
		                }
		            })
		        }else { //val为空时，还原数组
		          this.lectureoption = this.lectureoptionCopy;
		        }
			},
			handleAvatarSuccess(res, file) {
				if(res.code == 200) {
					this.courseImg = res.data[0];
				};
			},
			beforeAvatarUpload(file) {
				const isJPG = (file.type === 'image/jpeg') || (file.type === 'image/png');
				const isLt2M = file.size / 1024 / 1024 < 2;
				if(!isLt2M) {
					this.$message.error('上传图片大小不能超过 2MB!');
				}
				return isJPG && isLt2M;
			},
			getCoursewareLabel(){
				let permissType = 3;
				this.$rootFunction().userPermissions({permissType});
			},
			getUserPermissions(){
				let permissType = 4;
				this.$rootFunction().userPermissions({permissType});
			},
			getClassificationSystem(){
				let permissType = 6;
				this.$rootFunction().userPermissions({permissType});
			}
		},
		components: {
			alert,
			labelAll
		},
		mounted: function(){
			this.getParams();
			if(this.speakerId==null){
				this.$store.commit('GET_createTeacherWare');
				var s =this.$store.state.createTeacherWare;
				this.speakerId=s.speakerId
			}
			window.addEventListener("beforeunload",()=>{
				s={
					speakerId : this.speakerId
				}
				this.$store.commit('SET_createTeacherWare', s);
			});
			if(this.nowType == "edit") {
				console.log('306', this.nowType, this.$root.studyMapMsg);
				this.id = this.$root.studyMapMsg.id;
				this.rootcompanyid = this.$root.studyMapMsg.rootcompanyid;
				this.courseName = this.$root.studyMapMsg.courseName;
				this.permission = this. $root.studyMapMsg.knowledgeMapTypeId;
				this.speakerId = this.$root.studyMapMsg.speakerId;
				this.courseUpgradeScore = this.$root.studyMapMsg.courseUpgradeScore;
				this.courseImg = this.$root.studyMapMsg.courseImg;
				this.courseDesc = this.$root.studyMapMsg.courseDesc;
				if(this.$root.studyMapMsg.kejianLabel!=null){
					var arrnames=this.$root.studyMapMsg.kejianLabelName.split(",");
					this.LabelsNames=arrnames;
					var arrids=this.$root.studyMapMsg.kejianLabel.split(",");
					this.LabelsIds=arrids;
				};
				if(this.$root.studyMapMsg.userAttribute!=null){
					this.isopen=1;
					let userIds = this.$root.studyMapMsg.userAttribute.split(',');
					userIds.forEach(element => {
						this.checkedCities.push(parseInt(element));
						this.checkedSelectionIds.push(parseInt(element));
	                });
				}
			};
			this.$rootFunction().getRootCompangIdStatus();
			this.getCoursewareLabel();
			this.getUserPermissions();
			this.getClassificationSystem();
			this.$rootFunction().getAllLecture();
		}
	}
</script>

<style>
	.createWare{padding-bottom: 100px;}
	.coursewareContent{position: relative;}
	.createWare_line{margin-bottom: 20px;position: relative;}
	.createWare span{color: #333;}
	.createWare .tit{font-size: 16px;width: 80px;text-align: right;display: inline-block;height: 30px;line-height:30px;}
	.createWare input{width: 200px;height: 30px;line-height:30px;border: 1px solid #ccc;padding-left: 10px;color: #666;font-size: 14px;border-radius: 5px;}
	.createWare .el-select,.createWare .el-select .el-input,.createWare .el-select input{width: 212px;height: 32px;line-height: 32px;}
	.createWare .el-select .el-select__caret{height: 32px;line-height: 32px;}
	.createWare em{font-size:14px;color:#ccc;font-style:normal;}
	.createWare .el-checkbox{margin-right: 14px;}
	.createWare .teacherSkills {position:relative;height:34px;line-height:34px;margin-bottom: 0;}
	.createWare .skillDetail {width:450px;height:30px;line-height:30px;border:1px solid #ccc;border-radius:5px;position:absolute;top:0;left:86px;}
	.createWare .skillDetail i {font-style:normal;color:#ccc;position:relative;top:-4px;margin-left:4px;cursor:pointer;}
	.createWare .skillDetail span,.createWare .skillContent span {color:#44CEF6!important;font-size:14px;width:auto!important;margin-left:15px;cursor:pointer;}
	.createWare .skillContent {margin-left:86px;height:auto!important;width:607px;line-height:28px}
	.createWare .platformLogo{height: 100px!important;position: absolute;top: 0;left: 500px;width: 310px;}
	.createWare .platformImg{position: absolute;top: 0;left: 96px;}
	.createWare .platformImg .avatar-uploader{width: 100px;height: 100px;}
	.createWare .platformImg .avatar-uploader img{width: 100%;}
	.createWare .platformImg .avatar-uploader-icon{font-size:28px;color:#8c939d;width:100px;height:75px!important;padding-top:25px;text-align:center;background:#f2f2f2;    border-radius: 5px;}
	.createWare .platformImg .el-upload i em{font-size:14px;color:#ccc;font-style:normal;text-align:center;display:block;margin-top:6px;}
	.createWare .platformImg .rules{font-style:normal;font-size:12px;color:#ccc;margin-top:8px;display:block;line-height:16px;}
	.createWare_line .labelFour{width: 400px;height: 33px;line-height: 33px;border: 1px solid #ccc;border-radius: 5px 0 0 5px;display: inline-block;box-sizing: border-box;float: left;margin-left: 5px;}
	.createWare_line .labelFour span{position: relative;top: -2px;font-size: 14px;color: #333;margin-left: 16px;display: inline-block;}
	.createWare_line .openLabel{float: left;}
	.createWare_line .labelWarn{font-size: 12px;color: #999;margin-left: 87px;margin-top:10px}
	.createWare_line a.openLabel{width: 80px;height: 33px;line-height: 33px;display: inline-block;color: #fff;margin-left: -5px;background: #44CEF6;text-align: center;font-size: 14px;border-radius: 0 5px 5px 0;box-sizing: border-box;cursor: pointer;}
</style>